package com.zretc.emptraining.servlet;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html; charset=utf-8");
		String op = req.getParameter("op");
		String servlet = req.getParameter("servlet");
		System.out.println(op);
		System.out.println(servlet);
		Part file = req.getPart("upload");
		// 路径??
		String path = req.getServletContext().getRealPath("/upload/");
		System.out.println(path);
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		// 文件名
		System.out.println(file.getSubmittedFileName());
		String fn = file.getSubmittedFileName();
		if (fn.toLowerCase().endsWith(".jpg") || fn.toLowerCase().endsWith(".png")) {
			// getSubmittedFileName() 返回的是上传的文件名称
			// 生成文件新名字file.write(path+"/"+file.getSubmittedFileName());
			String nfn = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + fn.substring(fn.lastIndexOf("."));
			System.out.println("nfn:" + nfn);
			// 图片最终路径
			String PathPic = path + nfn;
			file.write(PathPic);
			System.out.println("PathPic:" + PathPic);
			req.setAttribute("filename", nfn);
			req.getRequestDispatcher(servlet+"?op=" + op).forward(req, res);
		} else {
			req.setAttribute("msg", "文件上传失败，必须为jpg或png图像文件");
			System.out.println("xxxxx");
		}
		
	}

}
